// 周视图模块
export function initWeekView(views, currentDate, invoke) {
  return {
    updateWeekView,
    renderWeekCalendar
  };

  // 更新周视图
  async function updateWeekView() {
    const weekStart = new Date(currentDate);
    weekStart.setDate(currentDate.getDate() - currentDate.getDay());
    const weekEnd = new Date(weekStart);
    weekEnd.setDate(weekStart.getDate() + 6);

    document.getElementById('current-week').textContent =
      `第${getWeekNumber(currentDate)}周 (${formatDate(weekStart)} - ${formatDate(weekEnd)})`;

    try {
      const todos = await invoke('get_todos_by_week', {
        weekStartDate: formatDate(weekStart)
      });
      renderWeekCalendar(todos);
    } catch (error) {
      console.error('加载周视图数据失败:', error);
    }
  }

  // 渲染周历
  function renderWeekCalendar(todos) {
    const grid = document.getElementById('week-grid');
    grid.innerHTML = '';

    const weekStart = new Date(currentDate);
    weekStart.setDate(currentDate.getDate() - currentDate.getDay());

    for (let i = 0; i < 7; i++) {
      const date = new Date(weekStart);
      date.setDate(weekStart.getDate() + i);

      const dayElement = document.createElement('div');
      dayElement.className = 'week-day';
      if (date.toDateString() === new Date().toDateString()) {
        dayElement.classList.add('today');
      }

      const header = document.createElement('div');
      header.className = 'week-day-header';
      header.textContent = `${formatDate(date)} 星期${['日', '一', '二', '三', '四', '五', '六'][i]}`;
      dayElement.appendChild(header);

      const todosContainer = document.createElement('div');
      todosContainer.className = 'week-day-todos';
      dayElement.appendChild(todosContainer);

      // 添加该日期的 Todo（如果有）
      if (todos && todos.length > 0) {
        const dayTodos = todos.filter(todo => {
          const todoDate = new Date(todo.due_time || todo.start_time);
          return todoDate.toDateString() === date.toDateString();
        });

        dayTodos.forEach(todo => {
          const todoElement = document.createElement('div');
          todoElement.className = `todo-item importance-${todo.importance.toLowerCase()}`;
          if (todo.completed) {
            todoElement.classList.add('completed');
          }

          const checkbox = document.createElement('input');
          checkbox.type = 'checkbox';
          checkbox.className = 'todo-checkbox';
          checkbox.checked = todo.completed;
          checkbox.addEventListener('change', () => toggleTodoCompletion(todo));
          todoElement.appendChild(checkbox);

          const content = document.createElement('div');
          content.className = 'todo-content';
          content.addEventListener('click', () => showTodoModal(todo));

          const title = document.createElement('div');
          title.className = 'todo-title';
          title.textContent = todo.title;
          content.appendChild(title);

          const meta = document.createElement('div');
          meta.className = 'todo-meta';

          if (todo.due_time) {
            const time = document.createElement('span');
            time.textContent = formatTime(new Date(todo.due_time));
            meta.appendChild(time);
          }

          if (todo.tags.length > 0) {
            const tagsContainer = document.createElement('div');
            tagsContainer.className = 'todo-tags';
            todo.tags.forEach(tag => {
              const tagElement = document.createElement('span');
              tagElement.className = 'tag';
              tagElement.textContent = tag;
              tagsContainer.appendChild(tagElement);
            });
            meta.appendChild(tagsContainer);
          }

          content.appendChild(meta);
          todoElement.appendChild(content);
          todosContainer.appendChild(todoElement);
        });
      }

      // 添加快速添加Todo的输入框
      const addInput = document.createElement('input');
      addInput.type = 'text';
      addInput.placeholder = '添加新事项...';
      addInput.className = 'week-add-input';
      addInput.addEventListener('keypress', async (e) => {
        if (e.key === 'Enter' && addInput.value.trim()) {
          try {
            await invoke('create_todo', {
              todo: {
                title: addInput.value.trim(),
                importance: 'C',
                urgency: 'C',
                start_time: formatDate(date) + 'T12:00',
                due_time: formatDate(date) + 'T18:00',
                tags: [],
                project_id: null,
                markdown_path: ""
              },
            });
            addInput.value = '';
            updateWeekView();
          } catch (error) {
            console.error('创建 Todo 失败:', error);
          }
        }
      });
      todosContainer.appendChild(addInput);

      grid.appendChild(dayElement);
    }
  }

  // TODO: 需要从utils导入这些工具函数
  function formatDate(date) {
    return date.toISOString().split('T')[0];
  }

  function formatTime(date) {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
    });
  }

  function getWeekNumber(date) {
    const firstDayOfYear = new Date(date.getFullYear(), 0, 1);
    const pastDaysOfYear = (date - firstDayOfYear) / 86400000;
    return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7);
  }
}